package cn.learn.async.unsafe;

/**
 * 线程不安全
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年05月30日18:16
 */
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "苦逼的我").start();
        new Thread(buyTicket, "牛逼的你们").start();
        new Thread(buyTicket, "可恶的黄牛党").start();
    }
}

class BuyTicket implements Runnable {
    /**
     * 公共的变量，所有线程共享，线程不安全
     */
    private int     ticketNums = 10;
    private boolean flag       = true;

    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    // 加 synchronized 就是安全的
    private  void  buy() {
        // 判断是否有票
        if (ticketNums < 0) {
            flag = false;
            return;
        }
        // 模拟买票延迟
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 买到票
        System.out.println(Thread.currentThread().getName() + "拿到了票" + ticketNums--);
    }

}
